package com.egs.witzbackend.game;

import java.util.ArrayList;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.egs.witzbackend.domain.Player;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class PlayerService {
		private PersistenceManagerFactory PMF;
		public PlayerService (PersistenceManagerFactory PMF) {
			this.PMF = PMF;
		}
		public Player RegisterPlayer(String playerId, String pushId) {
			PersistenceManager pm = PMF.getPersistenceManager();
			
			Player player = new Player(playerId, pushId);
			
			Key key = KeyFactory.createKey(Player.class.getSimpleName(), "playerId:" + playerId);
			player.setKey(key);
		    
			try {
	            pm.makePersistent(player);
	        } finally {
	            pm.close();
	        }
			
			return player;
		}

		public Player GetPlayer(String playerId) {
			PersistenceManager pm = PMF.getPersistenceManager();
			
			Key k = KeyFactory.createKey(Player.class.getSimpleName(), "playerId:" + playerId);
			
			Player player = null;
			try {
				player = pm.getObjectById(Player.class, k);
			} catch (JDOObjectNotFoundException e) {
				
			} finally {
	            pm.close();
	        }
			
			return player;
		}
		public ArrayList<String> GetPlayerIds() {
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Query q = new Query("Player");
			// PreparedQuery contains the methods for fetching query results
			// from the datastore
			PreparedQuery pq = datastore.prepare(q);
			ArrayList<String> playerIds = new ArrayList<String>();
			for (Entity result : pq.asIterable()) {
				String playerId = (String) result.getProperty("playerId");
				playerIds.add(playerId);
			}
			
			return playerIds;
		}
}
